package com.hd.crdao.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hd.crdao.MainActivity;
import com.hd.crdao.R;
import com.hd.crdao.adapter.HotAdapter;
import com.hd.crdao.base.BaseActivity;
import com.hd.crdao.bean.SearchBean;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.UIUtils;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 *
 *@author Administrator
 *@date 2017/5/31
 */
public class SearchActivity extends BaseActivity implements TextView.OnEditorActionListener {
    private static String TAG = "SearchActivity";
    @BindView(R.id.searchEt)
    EditText mSearchEt;
    @BindView(R.id.cancle)
    TextView mCancle;
    @BindView(R.id.clearTv)
    TextView mClearTv;
    @BindView(R.id.hotGv)
    GridView mHotGridView;
    @BindView(R.id.option)
    TextView mOption;
    @BindView(R.id.ll_hotbrand)
    LinearLayout mLlHotbrand;
    @BindView(R.id.id_flowlayout)
    TagFlowLayout mIdFlowlayout;  //流式布局
    public String[] mHotSearchArray;
    public String[] mHisSearchArray;
    private boolean flag = true;    //true为搜索车辆   false为搜索店铺
    public TagAdapter<String> mTagAdapter;
    public String[] mHisShopArray;

    @Override
    protected int getLayoutId() {
        return R.layout.seachview;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
    }

    @Override
    protected void initListener() {
        mHotGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String searchItem = mHotSearchArray[position];
                EventBus.getDefault().postSticky(new SearchBean(searchItem));
                SPUtils.saveString("check", "find");
                finish();
            }
        });

        mIdFlowlayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                if(flag){  //点击车辆搜索的历史条目
                    String s = mHisSearchArray[position];
                    EventBus.getDefault().postSticky(new SearchBean(s));
                    SPUtils.saveString("check", "find");
                    finish();
                }else {   //点击店铺搜索的历史条目
                    String s = mHisShopArray[position];
                    Intent i = new Intent(UIUtils.getContext(),SearchShopActivity.class);
                    i.putExtra("storeName",s);
                    startActivity(i);
                }
                return true;
            }
        });
        mSearchEt.setOnEditorActionListener(this);
    }

    @Override
    protected void initData() {
        //设置历史搜索的数据
        String hisSearch = SPUtils.getString("hisSearch", "");
        if (!TextUtils.isEmpty(hisSearch)) {
            setHisSearchArray(hisSearch);
        }

        //获取热门搜索的数据集  设置数据
        mHotSearchArray = UIUtils.getStrings(R.array.hotsearch);
        HotAdapter hotAdapter = new HotAdapter(mHotSearchArray);
        mHotGridView.setAdapter(hotAdapter);
    }


    /**
     * /设置历史车辆搜索的数据
     */
    public void setHisSearchArray(String hisSearch) {
        mHisSearchArray = hisSearch.split(",");
        mTagAdapter =new FlowLayoutAdapter(mHisSearchArray);
        mIdFlowlayout.setAdapter(mTagAdapter);
    }


    @OnClick({R.id.cancle, R.id.clearTv, R.id.option})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cancle:
                finish();
                break;
            case R.id.clearTv:
                if(flag){
                    SPUtils.saveString("hisSearch", "");
                }else {
                    SPUtils.saveString("hisShopSearch", "");
                }
                mHisSearchArray = new String[]{};
                mTagAdapter = new FlowLayoutAdapter(mHisSearchArray);
                mIdFlowlayout.setAdapter(mTagAdapter);
                mTagAdapter.notifyDataChanged();
                break;
            case R.id.option:
                showSearchTypePop();
                break;
        }
    }

    /**
     * 显示选择搜索类型的悬浮窗体
     */
    private void showSearchTypePop() {
        View contentView = LayoutInflater.from(SearchActivity.this).inflate(R.layout.popuplayout, null);
        LinearLayout llCar = (LinearLayout) contentView.findViewById(R.id.ll_car);
        LinearLayout llShop = (LinearLayout) contentView.findViewById(R.id.ll_shop);
        final PopupWindow popWnd = new PopupWindow();
        popWnd.setContentView(contentView);
        popWnd.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popWnd.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popWnd.setAnimationStyle(R.style.AnimationFade);
        popWnd.setFocusable(true);
        popWnd.setOutsideTouchable(false);// 设置允许在外点击消失
        ColorDrawable dw = new ColorDrawable(Color.WHITE);
        popWnd.setBackgroundDrawable(dw);
        popWnd.showAsDropDown(mOption);
        llCar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag = true;
                mSearchEt.setText("");
                String hisSearch = SPUtils.getString("hisSearch", "");
                if (!TextUtils.isEmpty(hisSearch)) {
                    mIdFlowlayout.setVisibility(View.VISIBLE);
                    setHisSearchArray(hisSearch);
                }else {
                    mIdFlowlayout.setVisibility(View.GONE);
                }
                mOption.setText("车辆");
                mSearchEt.setHint("请输入品牌车系搜索");
                mLlHotbrand.setVisibility(View.VISIBLE);
                popWnd.dismiss();
            }
        });

        llShop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag =false;
                mSearchEt.setText("");
                String hisShopSearch = SPUtils.getString("hisShopSearch", "");
                if (!TextUtils.isEmpty(hisShopSearch)) {
                    mIdFlowlayout.setVisibility(View.VISIBLE);
                    mHisShopArray = hisShopSearch.split(",");
                    mTagAdapter =new FlowLayoutAdapter(mHisShopArray);
                    mIdFlowlayout.setAdapter(mTagAdapter);
                }else {
                    mIdFlowlayout.setVisibility(View.GONE);
                }
                mSearchEt.setHint("请输入店铺名称搜索");
                mOption.setText("店铺");
                mLlHotbrand.setVisibility(View.GONE);   //隐藏热门搜索品牌的布局
                popWnd.dismiss();
            }
        });
    }

    /**
     * 软键盘搜索键的监听方法
     */
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {

            if(flag){    //车辆搜索
                String searchContent = mSearchEt.getText().toString().trim();
                String oldText = SPUtils.getString("hisSearch", "");        //取出之前存的值,默认值是空
                if (!TextUtils.isEmpty(searchContent) && !oldText.contains(searchContent + ",")) {    //如果搜索的文本不为空 并且之前存的不包括现在的
                    SPUtils.saveString("hisSearch", searchContent + "," + oldText);   //再存到sp
                }
                EventBus.getDefault().postSticky(new SearchBean(searchContent));
                SPUtils.saveString("check", "find");
                startActivity(new Intent(UIUtils.getContext(), MainActivity.class));
                finish();
            }else {  //店铺搜索
                String searchContent = mSearchEt.getText().toString().trim();
                String oldText = SPUtils.getString("hisShopSearch", "");        //取出之前存的值,默认值是空
                if (!TextUtils.isEmpty(searchContent) && !oldText.contains(searchContent + ",")) {    //如果搜索的文本不为空 并且之前存的不包括现在的
                    SPUtils.saveString("hisShopSearch", searchContent + "," + oldText);   //再存到sp
                }
                Intent i = new Intent(UIUtils.getContext(),SearchShopActivity.class);
                i.putExtra("storeName",searchContent);
                startActivityForResult(i,1);
            }
            return true;
        }
        return false;
    }

    /**
     *流式布局的适配器
     */
  private   class FlowLayoutAdapter extends TagAdapter<String> {

        public FlowLayoutAdapter(List<String> datas) {
            super(datas);
        }

        public FlowLayoutAdapter(String[] datas) {
            super(datas);
        }

        @Override
        public View getView(FlowLayout parent, int position, String s) {
            View view = View.inflate(UIUtils.getContext(), R.layout.flowlayout_item, null);
            TextView textView = (TextView) view.findViewById(R.id.item_tv);
            textView.setText(s);
            return view;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
        String hisShopSearch = SPUtils.getString("hisShopSearch", "");
        if (!TextUtils.isEmpty(hisShopSearch)) {
            mIdFlowlayout.setVisibility(View.VISIBLE);
            mHisShopArray = hisShopSearch.split(",");
            mTagAdapter =new FlowLayoutAdapter(mHisShopArray);
            mIdFlowlayout.setAdapter(mTagAdapter);
        }else {
            mIdFlowlayout.setVisibility(View.GONE);
        }
    }
}
